package com.sosee.cgfw.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.ad.ADJson;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.sosee.cgfw.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class Splash extends Activity {
    private TextView tv_version;//显示版本号
    private String mVersionName;//版本号
    private int mVersionCode;
    private String mDownLoadUrl;//apk下载地址
    private String mDesc;//apk描述
    private int currentVersionCode;//当前版本
    private TextView tv_progress;//下载进度条
    private SharedPreferences sp;
    private long beginTimer;//开始显示时间
    private HttpUtils httpUtils;

    private AlertDialog ad;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);
        init();
        getAD();
        beginTimer= SystemClock.currentThreadTimeMillis();
        goMain();
//        getWebInfo();
//        initDataBase();

    }


    public void getAD(){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.AD_URL, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Constans.aList = JSONArray.parseArray(responseInfo.result, ADJson.class);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast(getString(R.string.internet_error));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        goMain();
    }

    /**
     * 初始化闪屏页面的业务
     */
    public void init(){
        httpUtils=new HttpUtils();
        tv_version= (TextView) findViewById(R.id.tv_version);
        PackageInfo info=getPackageInfo(getPackageName());
        if(info!=null){
            tv_version.setText("版本号"+info.versionName);
        }
        currentVersionCode=info.versionCode;
        LogUtils.log_E("current"+currentVersionCode);
        tv_progress= (TextView) findViewById(R.id.progress);
        sp=getSharedPreferences("setting",MODE_PRIVATE);
    }

    /**
     * 获取指定app信息
     * @param packName
     * @return
     */
    public PackageInfo getPackageInfo(String packName){
        PackageManager pm=getPackageManager();
        PackageInfo info=null;
        try {
            info=pm.getPackageInfo(packName,0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info;
    }
    private String qiangZhi;

    /**
     * 获取网络数据
     */
    public void getWebInfo(){
        HttpUtils http=new HttpUtils();

        http.send(HttpRequest.HttpMethod.GET, Constans.UPDATEURL,new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> ResponseInfo) {
                JSONObject json= null;
                try {
                    //获取成功后解析json字符串
                    json = new JSONObject(ResponseInfo.result);
                    //是否强制用户跟新
                    qiangZhi=json.getString("policy");
                    mVersionName=json.getString("versionName");
                    mVersionCode=json.getInt("code");
                    mDesc=json.getString("desc");
                    mDownLoadUrl=json.getString("downloadUrl");
                    //如果发现新版本，则显示对话框提示用户更新
                    if(mVersionCode>currentVersionCode){
                        showDialog();
                    }else{
                        goMain();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtils.log_E("splash"+e.toString());
                }
                LogUtils.log_E("版本号："+mVersionCode);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(Splash.this,"网络异常",Toast.LENGTH_SHORT).show();
                goMain();
            }
        });
    }
    public void showDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        View view=View.inflate(this,R.layout.dialog_update,null);
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView tv_title= (TextView) view.findViewById(R.id.tv_title);
        TextView tv_msg= (TextView) view.findViewById(R.id.tv_msg);
        tv_title.setText("发现新版本："+mVersionName);
        tv_msg.setText(mDesc);
        Button bt_wait= (Button) view.findViewById(R.id.bt_wait);
        Button bt_down= (Button) view.findViewById(R.id.bt_down);
        bt_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoad(mDownLoadUrl);
                ad.dismiss();
            }
        });
        bt_wait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("yes".equals(qiangZhi)) {
                    finish();
                } else {
                    goMain();
                    ad.dismiss();
                }

            }
        });
        builder.setCancelable(false);
        builder.setView(view);
        ad=builder.create();
        ad.show();
        /*builder.setView(view);
        builder.setTitle("发现新版本："+mVersionName)
                .setMessage(mDesc)
                .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        downLoad(mDownLoadUrl);
                    }
                })
                .setCancelable(false)//用户点返回无效
                .setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //跳转到程序主页面
                        goMain();
                    }
                }).show();*/
    }

    /**
     * 跳转到主页面
     */
    public void goMain(){
        long endtim=SystemClock.currentThreadTimeMillis();
        long t=endtim-beginTimer;
        if(t<2000){
          handler.sendMessageDelayed(Message.obtain(),2000-t);
        }else{
            handler.sendEmptyMessage(0);
        }

    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = new Intent(Splash.this, SplashAdActivity.class);
            startActivity(intent);
            finish();
        }
    };

    /**
     * 下载到sd卡中
     */
    public void downLoad(String downloadurl){
        HttpUtils http=new HttpUtils();
        //先判断sd卡有没有挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //下载位置
            String target= Environment.getExternalStorageDirectory()+"/update.apk";
            http.download(downloadurl,target, new RequestCallBack<File>() {
                @Override
                public void onSuccess(ResponseInfo<File> stringResponseInfo) {
                    Toast.makeText(Splash.this,"下载成功",Toast.LENGTH_SHORT).show();
                    inStallApk(stringResponseInfo.result);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Toast.makeText(Splash.this,"下载失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    tv_progress.setVisibility(View.VISIBLE);
                    tv_progress.setText("下载进度："+current*100/total+"%");
                }
            });
        }else{
            Toast.makeText(this,"您没有安装sd卡哦",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 安装apk
     * @param result
     */
    public void inStallApk(File result){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(Uri.fromFile(result),
                "application/vnd.android.package-archive");
        startActivityForResult(intent, 0);
    }

    //初始化数据库
    public void initDataBase(){
        copyDB("antivirus.db");
        AssetManager am=getAssets();
        InputStream is=null;
        FileOutputStream fos=null;
        File file=new File(getFilesDir(),"address.db");
        Toast.makeText(this,"create"+file.length(),Toast.LENGTH_SHORT).show();
        try {
            is=getAssets().open("address.db");
            fos=new FileOutputStream(file);
            byte[] by=new byte[1024];
            int length=0;
            while((length=is.read(by))!=-1){
                fos.write(by,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(fos!=null)
                    fos.close();
                if(is!=null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 拷贝资产目录下的数据库文件
     * @param dbname  数据库文件的名称
     */
    private void copyDB(final String dbname) {
        new Thread(){
            public void run() {
                try {
                    File file = new File(getFilesDir(),dbname);
                    if(file.exists()&&file.length()>0){
                        return ;
                    }
                    InputStream is = getAssets().open(dbname);
                    FileOutputStream fos  = openFileOutput(dbname, MODE_PRIVATE);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len = is.read(buffer))!=-1){
                        fos.write(buffer, 0, len);
                    }
                    is.close();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }




}
